/**
 * @fileoverview
 * This script defines a generic service class for running SPARQL queries.
 * @author <a href="http://purl.org/net/aliman">Alistair Miles</a>
 * @version $Revision:538 $ on $Date: 2008-08-27 09:08:41 +0100 (Wed, 27 Aug 2008) $ by $Author: aliman $
 * @requires flyui.util
 * @requires flyui.sparql.Service
 * @requires YAHOO.util.Connect
 * For license terms see http://flyui.googlecode.com
 */


flyui.namespace("flyui.sparql");


/**
 * @class
 */
flyui.sparql.Service = function() {};


/**
 * @param {String} url
 */
flyui.sparql.Service.prototype.setEndpoint = function( url ) {
    this._endpoint = url;
};


/**
 * @private
 * @type String
 */
flyui.sparql.Service.prototype._endpoint = null;


/**
 * @param {String} query
 * @param {Function} success
 * @param {Function} failure
 */
flyui.sparql.Service.prototype.query = function( query, success, failure ) {

    flyui.info("flyui.sparql.Service.query: "+query);
    
    // define the callback object
    var callback = {
        success: success,
        failure: failure
    };
            
    var url = this._buildURL(query);
    
    flyui.debug("spike string length, expect 4: "+"abcd".length);
    flyui.debug("url length: "+url.length);
    
    flyui.debug("flyui.sparql.Service :: make the request to "+url);
    
	YAHOO.util.Connect.initHeader("Accept", "application/sparql-results+json", true);    
    YAHOO.util.Connect.asyncRequest("GET", url, callback);
    
};

flyui.sparql.Service.prototype.postQuery = function( query, success, failure ) {
    flyui.info("flyui.sparql.Service.postQuery: "+query);
    
    // define the callback object
    var callback = {
        success: success,
        failure: failure
    };
            
    var url = this._endpoint;
    
//    flyui.debug("spike string length, expect 4: "+"abcd".length);
//    flyui.debug("url length: "+url.length);    
    flyui.debug("flyui.sparql.Service :: make the request to "+url);
    
    // output=json not necessary for sparqlite, but keep for compatibility with virtuoso
    var content = "query="+escape(query)+"&output=json";
	
	YAHOO.util.Connect.initHeader("Accept", "application/sparql-results+json", true);    
    YAHOO.util.Connect.asyncRequest("POST", url, callback, content);
    
}


/**
 * @private
 * @param {String} query
 * @type String
 */
flyui.sparql.Service.prototype._buildURL = function( query ) {
    return this._endpoint + "?output=json&query=" + escape(query);
}


